module ecs {
    /**
     * 
     */
    export class FieldHandler{
        private _cache: InjectionCache;
        public fieldResolvers: Bag<FieldResolver>;

        constructor(cache: InjectionCache, fieldResolvers?: Bag<FieldResolver>){
            this._cache = cache;
            if (fieldResolvers){
                this.fieldResolvers = fieldResolvers;
            }else{
                this.fieldResolvers = new Bag<FieldResolver>();
            }
            
        }

        /**
         * 使用提供的fieldResolvers构造一个新的FieldHandler。当需要完全控制{@link FieldResolver}顺序时，应该使用这个构造函数。
         * @param world 
         * @param injectables 
         */
        public initialize(world: World, injectables: {[s: string]: Object}){
            let fieldResolveFound = false;
            for (let i = 0, s = this.fieldResolvers.size(); i < s; i ++){
                let fieldResolver = this.fieldResolvers.get(i);
                if (egret.is(fieldResolver, "UseInjectionCache")){
                    (fieldResolver as any).setCache(this._cache);
                }

                if (egret.is(fieldResolver, "PojoFieldResolver")){
                    (fieldResolver as any).setPojos(injectables);
                    fieldResolveFound = true;
                }

                fieldResolver.initialize(world);
            }

            if (injectables && Object.keys(injectables).length != 0 && !fieldResolveFound){
                throw new Error("FieldHandler lacks resolver capable of dealing with your custom injectables. Register a WiredFieldResolver or PojoFieldResolver with your FieldHandler");
            }
        }

        /**
         * 
         * @param fieldResolver 
         */
        public addFieldResolver(fieldResolver: FieldResolver){
            this.fieldResolvers.add(fieldResolver);
        }
    }
}